const { ResponseCode } = require('../utils/mapping');
const Router = require('koa-router');
const { verifyRouter } = require('../utils/jwt');
const tokenRouter = require('./routers/token');
const userRouter = require('./routers/user');
const uploadRouter = require('./routers/upload');

const router = new Router();

router.prefix('/api');

// 注册自定义统一处理中间件
router.use(async (ctx, next) => {
	// 处理跨域
	ctx.set('Access-Control-Allow-Origin', 'http://localhost:1085');

	await next();

	// 处理响应消息
	if (!ctx.body) {
		ctx.body = {
			code: ctx.status,
			data: null,
		};
	}
	if (ctx.body.code === undefined) {
		ctx.body.code = ctx.status;
	}
	if (ctx.body.data === undefined) {
		ctx.body.data = null;
	}
	if (!ctx.body.msg) {
		ctx.body.msg = ResponseCode[ctx.body.code];
	}
});

// 生成token的接口不需要验证token，所以写在前面
router.use('/token', tokenRouter.routes());

// 注册token验证中间件
router.use(verifyRouter);

router.use('/user', userRouter.routes());
router.use('/upload', uploadRouter.routes());

module.exports = router;
